package com.inibb.app.util.mail;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.message.GenericMessage;
import org.springframework.mail.javamail.MimeMailMessage;

public class MailService {
	private final Log logger = LogFactory.getLog(this.getClass());
	
	public MimeMailMessage formatMail(GenericMessage<MimeMessage> msg) {
		
		try {
			MimeMessage mimemsg = msg.getPayload();
			MimeMailMessage mimeMailMsg = new MimeMailMessage(mimemsg);
			return mimeMailMsg;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return null;
		}
		
	}

	public MimeMailMessage onMailFailed(MimeMessage me) {

		try {
			logger.error("Message was unable to send due to mail server connection error");
			logger.error("Subject: " + me.getSubject());
			Address[] addresses = me.getRecipients(Message.RecipientType.TO);
			for (Address address: addresses) {
				logger.error("To Address: " + address);
			}
			
			// This will be called for messages that fail during email sending. We just
		    // log the error and delete the message that failed. If we don't delete the
		    // message it will remain in the queue and be continually redelivered
		    // until it succeeds (which could be never).

			//MimeMailMessage mimeMailMsg = new MimeMailMessage(me);
			//return mimeMailMsg;
			return null;
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
		
	}

}
